import Vue from "vue";
import VueRouter from "vue-router";
import { isArray, isString } from "@/global/type";
import errorPage from "@/404";
Vue.use(VueRouter);

/**
 * 创建页面路由
 * @param {String/Array} path 项目目录名称/路由列表
 * @param {VUEComponent} view 引入页面模版()
 */
const createRoute = (path, view) => {
  let routes;
  if (isArray(path)) {
    routes = path;
  } else if (isString(path) && view) {
    routes = [
      {
        path: "/" + path,
        name: path,
        component: view
      }
    ];
  } else {
    throw "路由配置参数有误";
  }
  routes.push({
    path: "/404",
    name: "404",
    component: errorPage
  });
  const router = new VueRouter({
    mode: "history",
    base: process.env.BASE_URL,
    routes
  });
  router.beforeEach((to, from, next) => {
    /**
     * 待处理地址栏参数
     */
    if (to.matched.length) {
      next();
    } else {
      next({ path: "/404", replace: true });
    }
  });
  return router;
};

export default createRoute;
